# -*- coding: utf-8 -*-
#!/usr/bin/env python

import pylab
import numpy
import scipy, math

import atpy

tbl = atpy.Table('final_params_lowchi.vot')
tbl.sort('BmV')
Vmag=[]; BmV=[]; LEID=[]

params_found = open('distance.out','w')

for i in range(len(tbl)):
	LEID.append(tbl.data['LEID'][i])
	Vmag.append(tbl.data['V'][i])
	BmV.append(tbl.data['BmV'][i])
	
polycoeffs = scipy.polyfit(BmV,Vmag,4)

print polycoeffs

V_fit = scipy.polyval(polycoeffs, BmV)

params_found.write('LEID,BmV,V,distance\n')
for i in range(len(Vmag)):
	BmV_curve=0.7
	distance_old=99
	distance_min=99
	for BmV_curve in range(60,160):
		BmV_curve=float(BmV_curve)/100
		distance_new=(math.sqrt(math.pow((BmV_curve-BmV[i]),2)+math.pow((scipy.polyval(polycoeffs, BmV_curve)-Vmag[i]),2)))
		if abs(distance_new)>abs(distance_old):
			if BmV_curve>BmV[i]:
				distance_new=distance_new*-1
			break
		distance_old=distance_new
	params_found.write(str(LEID[i])+','+str(BmV[i])+','+str(Vmag[i])+','+str(distance_new)+'\n')
	

pylab.figure(1)

pylab.plot(BmV, Vmag, 'k.')
#pylab.plot(BmV[i], Vmag[i], 'g*')
#pylab.plot(BmV_curve, scipy.polyval(polycoeffs, BmV_curve), 'g*')
pylab.plot(BmV, V_fit, 'r-')
pylab.show()

#pylab.savefig('randnhist.png')
